<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/12/7
 * Time: 4:07 PM
 */

namespace app\admin\controller;


use app\model\AccountCapitalFlow;
use app\model\TravelPeople;
use extend\Functions;
use extend\IDValidator;
use extend\STATUS_CODE;
use think\Request;

class Member extends Auth
{
    /**
     * @purpose 添加用户
     * @param Request $request
     * @return array
     */
    public function create (Request $request)
    {
        $data   = $request->post();
        if (!$data['username']) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入用户名'
            );
        }
        if ($data['mobile'] && !Functions::check_mobile($data['mobile'])) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '手机号码格式错误'
            );
        }
        if (!$data['password']) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入密码'
            );
        }
        // 检查用户名
        if (\app\model\Member::M()->where('username', $data['username'])-> count() > 0) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '用户名已存在'
            );
        }
        if ($data['mobile'] && \app\model\Member::M()->where('mobile', $data['mobile'])-> count() > 0) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '手机号码已存在'
            );
        }
        $member_data                    = Functions::password(strtolower(trim($data['password'])));
        if ($data['nickname']) {
            $member_data['nickname'] = $data['nickname'];
        }
        if ($data['mobile']) {
            $member_data['mobile'] = $data['mobile'];
        }
        // 生产用户uuid
        $member_data['uuid'] = strtolower(Functions::getUUID());
        RE_UUID:
        $member_data['uuid'] = strtolower(Functions::getUUID());
        if (\app\model\Member::M()->where('uuid', $member_data['uuid'])->count(1) > 0) {
            goto RE_UUID;
        }
        $member_data['username']       = strtolower($data['username']);
        $member_data['create_ip']       = $request->ip();
        $member_data['last_login_ip']   = $request->ip();
        $member_data['now_ip']          = $request->ip();
        $member_data['last_login_time'] = time();
        $member_data['now_time']        = time();
        $result = \app\model\Member::M()
            ->isUpdate(false)
            ->data($member_data)
            ->save();
        if ($result) {
            return self::response();
        }
        return self::response(
            STATUS_CODE::CREATE_FAIL,
            '添加失败'
        );
    }
    /**
     * @purpose 余额操作
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function recharge (Request $request)
    {
        $quota  = (float) $request->post('quota');
        $uid    = $request->post('uid');
        $remark    = $request->post('remark');
        $quota  = (int) ($quota * 100);
        if ($quota === 0) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '充值额度不可为0'
            );
        }
        if (!$remark) {
            return self::response(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少备注'
            );
        }
        \app\model\Member::M()->startTrans();
        $member_info    = \app\model\Member::M()
            ->where('uid', $uid)
            ->field('uid,balance,frozen')
            ->find();
        if (!$member_info) {
            \app\model\Member::M()->rollback();
            return self::response(
                STATUS_CODE::FAIL,
                '用户不存在'
            );
        }
        if ($quota < 0 && ($member_info->balance - $member_info->frozen) < abs($quota)) {
            \app\model\Member::M()->rollback();
            return self::response(
                STATUS_CODE::FAIL,
                '当前用户可扣除的余额不足'
            );
        }
        // 操作用户约
        $member_result = \app\model\Member::M()
            ->where('uid', $uid)
            ->setInc('balance', $quota);
        // 记录账户资金流水
        $account_capital_flow = AccountCapitalFlow::M()
            ->data([
                'uid' => $uid,
                'quota' => abs($quota),
                'type' => $quota > 0 ? 1 : 2,
                'balance' => $quota + ($member_info->balance - $member_info->frozen),
                'descriptions' => ($quota > 0 ? '充值余额' :  '扣除余额').'-管理员['.(self::$user_info['name'] ? self::$user_info['name'] : self::$uid).']手动操作,备注:【'.$remark.'】'
            ])
            ->save();
        // 记录支付账单
        $bill_result = \app\model\Bill::addToBill(
            $uid,
            ($quota > 0 ? 5 : 6),
            '',
            abs($quota),
            11,
            ($quota > 0 ? '充值余额' :  '余额扣除').'-管理员['.(self::$user_info['name'] ? self::$user_info['name'] : self::$uid).']手动操作,备注:【'.$remark.'】'
        );
        if ($member_result && $account_capital_flow && $bill_result) {
            \app\model\Member::M()->commit();
            return self::response();
        }
        \app\model\Member::M()->rollback();
        return $this->response(
            STATUS_CODE::FAIL,
            '操作失败'
        );
    }
    /**
     * @purpose 编辑出行人
     * @param Request $request
     * @return array
     */
    public function editTravel (Request $request)
    {
        $data       = $request->post();
        $data['certificate_number'] = strtoupper($data['certificate_number']);
        if ($data['certificate_type'] === 1) {
            $validate = IDValidator::getInstance();
            if (!$validate->isValid($data['certificate_number'])) {
                return self::response(
                    STATUS_CODE::PARAMETER_ERROR,
                    '无效的身份证号码'
                );
            }
        }
        $result = TravelPeople::M()
            ->allowField(true)
            ->save($data, ['id' => $data['id']]);
        if ($result) {
            return self::response();
        }
        return self::response(
            STATUS_CODE::UPDATE_FAIL,
            '编辑失败'
        );
    }
    /**
     * @purpose 获取会员出行人列表
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function travel (Request $request)
    {
        $page       = $request->get('page', 1);
        $size       = $request->get('size', 20);
        $uid        = $request->get('uid');
        $kw         = $request->get('kw', '');
        $where      = [];
        $where[]    = ['uid', '=', $uid];
        $where[]    = ['name', ['like', '%'.$kw], ['like', '%'.$kw.'%'], ['like', $kw.'%'], 'or'];
        $total      = TravelPeople::M()
            ->where($where)
            ->count(1);
        $list       = TravelPeople::M()
            ->where($where)
            ->page($page, $size)
            ->field('id,uid,name,sex,type,mobile,certificate_type,certificate_number')
            ->select();
        return self::response([
            'total' => $total,
            'list' => $list
        ]);
    }
    /**
     * @purpose 获取账户余额流水明细
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function balanceDetail (Request $request)
    {
        $page       = $request->get('page', 1);
        $size       = $request->get('size', 20);
        $uid        = $request->get('uid');
        $total      = AccountCapitalFlow::M()
            ->where('uid', $uid)
            ->count(1);
        $list       = AccountCapitalFlow::M()
            ->where('uid', $uid)
            ->page($page, $size)
            ->order('create_at desc')
            ->field('id,uid,quota,balance,type,descriptions,FROM_UNIXTIME(create_at, "%Y-%m-%d %H:%i:%s") as create_date')
            ->select();
        return self::response([
            'total' => $total,
            'list' => $list
        ]);
    }
    /**
     * @purpose 获取会员账单记录
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bill (Request $request)
    {
        $page       = $request->get('page', 1);
        $size       = $request->get('size', 20);
        $uid        = $request->get('uid');
        $total      = \app\model\Bill::M()
            ->where('uid', $uid)
            ->count(1);
        $items      = \app\model\Bill::M()
            ->where('uid', $uid)
            ->order('create_at desc')
            ->field('id,uid,type,order_no,quota,pay_method,descriptions,
            FROM_UNIXTIME(create_at, "%Y-%m-%d %H:%i:%s") as create_date')
            ->page($page, $size)
            ->select();
        return self::response([
            'total' => $total,
            'list' => $items
        ]);
    }
    /**
     * @purpose 获取用户详情
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail (Request $request)
    {
        $uid        = $request->get('uid');
        $info       = \app\model\Member::M()
            ->with('wechatInfo')
            ->where('uid', $uid)
            ->field('uid,mobile,username,nickname,avatar,balance,frozen,create_ip,now_ip,now_time,sex,
            FROM_UNIXTIME(create_at, "%Y-%m-%d %H:%i:%s") as create_date,FROM_UNIXTIME(now_time, "%Y-%m-%d %H:%i:%s") as now_date')
            ->find();
        return self::response($info);
    }
    /**
     * @purpose 获取用户列表
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function items (Request $request)
    {
        $page       = $request->get('page', 1);
        $size       = $request->get('size', 20);
        $searchType = (int) $request->get('searchType', 0);
        $searchValue = $request->get('searchValue');
        $where = [];
        if ($searchType) {
            switch ($searchType) {
                case 1: // 用户名
                    $where[] = ['username', ['like', '%'.$searchValue], ['like', '%'.$searchValue.'%'], ['like', $searchValue.'%'], 'or'];
                    break;
                case 2: // 用户昵称
                    $where[] = ['nickname', ['like', '%'.$searchValue], ['like', '%'.$searchValue.'%'], ['like', $searchValue.'%'], 'or'];
                    break;
                case 3: // 用户手机号码
                    $where[] = ['mobile', '=', $searchValue];
                    break;
            }
        }
        $total      = \app\model\Member::M()
            ->where($where)
            ->count(1);
        $list       = \app\model\Member::M()
            ->with('wechat')
            ->where($where)
            ->field('uid,uuid,mobile,balance,frozen,username,nickname,avatar,sex,
            FROM_UNIXTIME(create_at, "%Y-%m-%d %H:%i:%s") as create_date')
            ->order('create_at desc')
            ->page($page, $size)
            ->select();
        return $this->response([
            'total' => $total,
            'list' => $list
        ]);
    }

    /**
     * @purpose 重置用户登录密码
     * @param Request $request
     * @return array
     */
    public function resetPassword (Request $request)
    {
        $password       = $request->post('password');
        $uid            = $request->post('uid');
        if (!$password) {
            return $this->response(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入密码'
            );
        }
        $password  = Functions::password(strtolower($password));
        $result = \app\model\Member::M()
            ->isUpdate(true)
            ->save($password, ['uid' => $uid]);
        if ($result) {
            return $this->response();
        }
        return $this->response(
            STATUS_CODE::UPDATE_FAIL,
            '修改失败'
        );
    }
    /**
     * @purpose 重置用户登录密码
     * @param Request $request
     * @return array
     */
    public function resetMobile (Request $request)
    {
        $mobile       = $request->post('mobile');
        $uid            = $request->post('uid');
        if (!$mobile) {
            return $this->response(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入手机号码'
            );
        }
        if (!Functions::check_mobile($mobile)) {
            return $this->response(
                STATUS_CODE::PARAMETER_ERROR,
                '手机号码格式错误'
            );
        }
        if (\app\model\Member::M()->where([
            ['mobile', '=', $mobile],
            ['uid', '<>', $uid]
        ])->count(1)) {
            return $this->response(
                STATUS_CODE::PARAMETER_ERROR,
                '该手机号码已绑定其他账号'
            );
        }
        $result = \app\model\Member::M()
            ->isUpdate(true)
            ->save(['mobile' => $mobile], ['uid' => $uid]);
        if ($result) {
            return $this->response();
        }
        return $this->response(
            STATUS_CODE::UPDATE_FAIL,
            '修改失败'
        );
    }

    /**
     * @purpose 重置用户名
     * @param Request $request
     * @return array
     */
    public function resetUsername (Request $request)
    {
        $username       = $request->post('username');
        $uid            = $request->post('uid');
        if (!$username) {
            return $this->response(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入用户名'
            );
        }
        $username = strtolower(trim($username));
        if (!preg_match('/^(?!\d+$)[\da-zA-Z]{6,12}$/', $username)) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '用户名格式错误，由6位以上，字母或数字组合'
            );
        }
        if (\app\model\Member::M()->where([
            ['username', '=', $username],
            ['uid', '<>', $uid]
        ])->count(1)) {
            return $this->response(
                STATUS_CODE::PARAMETER_ERROR,
                '用户名已存在'
            );
        }
        $result = \app\model\Member::M()
            ->isUpdate(true)
            ->save(['username' => $username], ['uid' => $uid]);
        if ($result) {
            return $this->response();
        }
        return $this->response(
            STATUS_CODE::UPDATE_FAIL,
            '修改失败'
        );
    }
}